package com.uxwine.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Environment;

public class Log {
	
	private static final boolean DEBUG = false;
	public static final String TAG = "cleaner.LOG";
	static final SimpleDateFormat FMT_HMS = new SimpleDateFormat("HH:mm:ss");
	static final SimpleDateFormat FMT_YMD = new SimpleDateFormat("yyyy-MM-dd");
	static final File ROOT = Environment.getExternalStorageDirectory();
	
	public static void d(String tag, String msg)
	{
		android.util.Log.d(tag, msg);
	}
	
	public static void d(Exception e)
	{
		e.printStackTrace();
	}
	
	public static void e(Exception e)
	{
		e.printStackTrace();
	}
	
	public static void e(String tag, String msg)
	{
		android.util.Log.e(tag, msg);
	}
	public static void i(String tag, String msg)
	{
		android.util.Log.i(tag, msg);
	}
	public static void w(String tag, String msg)
	{
		android.util.Log.w(tag, msg);
	}
	
	public synchronized static void f(String tag, String msg)
	{
		if(DEBUG)
			writeToFile(tag, msg);
	}
	
	public synchronized static void f(String tag, Exception e)
	{
		if(DEBUG)
			writeToFile(tag, e);
	}
	
	private static void writeToFile(String tag, Exception e)
	{
		Date now = new Date();
		String path = FMT_YMD.format(now);
		if(!ROOT.exists())
			return;
		File file = new File(ROOT, path + "." + tag + ".txt");
		try
		{
			PrintWriter pw = new PrintWriter(file, "UTF-16");
			e.printStackTrace(pw);
			pw.close();
		} 
		catch (IOException ex){}
	}
	
	private static void writeToFile(String tag, String msg)
	{
		Date now = new Date();
		String path = FMT_YMD.format(now);
		String text = FMT_HMS.format(now) + "	" + msg;
		if(!ROOT.exists())
			return;
		File file = new File(ROOT, path + "." + tag + ".txt");
		try
		{
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true), "UTF-16" ));
			out.write(text);
			out.write("\r\n");
			out.close();
		} 
		catch (IOException e){}
	}
}
